﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebUI.Controls
{
    public partial class ImageCropper : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (!System.IO.File.Exists(Server.MapPath(OriginalImageURL)))
                    OriginalImageURL = hidDefaultPic.Value;
                if (!System.IO.File.Exists(Server.MapPath(ThumbImageURL)))
                    ThumbImageURL = hidDefaultPic.Value;
                if (!System.IO.File.Exists(Server.MapPath(OutputURL)))
                    OutputURL = hidDefaultPic.Value;
            }
        }

        public string ThumbImageURL
        {
            get
            {
                return CropMe.ImageUrl;
            }
            set
            {
                CropMe.ImageUrl = value;
                if (System.IO.File.Exists(Server.MapPath(value)))
                {
                    TopID.Value = "0";
                    LeftID.Value = "0";
                }
            }
        }

        public string OutputURL
        {
            get
            {
                if(!System.IO.File.Exists(Server.MapPath(Output.ImageUrl)))
                    Output.ImageUrl = hidDefaultPic.Value;
                return Output.ImageUrl;
            }
            set
            {
                Output.ImageUrl = value;
            }
        }

        public Unit Width
        {
            get
            {
                return CropFrom.Width;
            }
            set
            {
                CropFrom.Width = value;
            }
        }

        public Unit Height
        {
            get
            {
                return CropFrom.Height;
            }
            set
            {
                CropFrom.Height = value;
            }
        }

        public int Top
        {
            get
            {
                return -int.Parse(TopID.Value);
            }
        }

        public int Left
        {
            get
            {
                return -int.Parse(LeftID.Value);
            }
        }

        public int ScaleRate
        {
            get
            {
                try
                {
                    return (int)(1.0 * ScaleWidth / OriginalWidth * 100);
                }
                catch (Exception ex)
                {
                    return 100;
                }
            }
        }

        public string WorkingDirectory
        {
            get 
            {
                return ViewState[ClientID + "TempDirectory"] != null ? ViewState[ClientID + "TempDirectory"].ToString() : ""; 
            }
            set
            {
                ViewState[ClientID + "TempDirectory"] = value;
            }
        }

        public string OriginalImageURL
        {
            get 
            {
                return ViewState[ClientID + "OrgImageURL"] != null ? ViewState[ClientID + "OrgImageURL"].ToString() : ""; 
            }
            set
            {
                ViewState[ClientID + "OrgImageURL"] = value;
                ThumbImageURL = value;
            }
        }

        public int ScaleWidth
        {
            get
            {
                return txtWidth.Text != "" ? int.Parse(txtWidth.Text) : 0;
            }
            set
            {
                txtWidth.Text = value.ToString();
            }
        }

        public int ScaleHeight
        {
            get
            {
                return txtHeight.Text != "" ? int.Parse(txtHeight.Text) : 0;
            }
            set
            {
                txtHeight.Text = value.ToString();
            }
        }

        public int OriginalWidth
        {
            get
            {
                return OrgWidth.Value != "" ? int.Parse(OrgWidth.Value) : 0;
            }
            set
            {
                OrgWidth.Value = value.ToString();
            }
        }

        public int OriginalHeight
        {
            get
            {
                return OrgHeight.Value != "" ? int.Parse(OrgHeight.Value) : 0;
            }
            set
            {
                OrgHeight.Value = value.ToString();
            }
        }

        public string Description
        {
            get
            {
                return txtDesc.Text;
            }
            set
            {
                txtDesc.Text = value;
            }
        }

        public void btnUpFile_OnClick(object sender, EventArgs e)
        {
            if (fileUpload.HasFile)
            {
                string tempDir = GetTempDir();
                string fileName = tempDir + "//" + Guid.NewGuid().ToString() + System.IO.Path.GetExtension(fileUpload.PostedFile.FileName);
                fileUpload.SaveAs(Server.MapPath(fileName));
                OriginalImageURL = fileName;
                ThumbImageURL = fileName;

                System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(Server.MapPath(fileName));
                OriginalHeight = bmp.Height;
                OriginalWidth = bmp.Width;

                Scale(100);
            }
        }

        public void btnGenerateMe_OnClick(object sender, EventArgs e)
        {
            GetThumb();
        }

        private void GetThumb()
        {
            if (System.IO.File.Exists(Server.MapPath(ThumbImageURL)))
            {
                System.Drawing.Image srcBitmap = new System.Drawing.Bitmap(Server.MapPath(ThumbImageURL));
                System.Drawing.Image bmp = ImageProcessor.CropImage(srcBitmap, Left, Top, (int)Width.Value, (int)Height.Value);
                string tempDir = GetTempDir();
                string fileName = tempDir + "//" + Guid.NewGuid().ToString() + System.IO.Path.GetExtension(ThumbImageURL);
                bmp.Save(Server.MapPath(fileName));
                OutputURL = fileName;
            }
        }

        public void LoadImage(string url)
        {
            OriginalImageURL = url;
            GetThumb();
        }

        private void Scale(int rate)
        {
            if (System.IO.File.Exists(Server.MapPath(OriginalImageURL)))
            {
                System.Drawing.Image srcBitmap = new System.Drawing.Bitmap(Server.MapPath(OriginalImageURL));
                System.Drawing.Image bmp = ImageProcessor.ScaleImage(srcBitmap, rate);
                string tempDir = GetTempDir();
                string fileName = tempDir + "//" + Guid.NewGuid().ToString() + System.IO.Path.GetExtension(OriginalImageURL);

                bmp.Save(Server.MapPath(fileName));
                ThumbImageURL = fileName;

                ScaleHeight = bmp.Height;
                ScaleWidth = bmp.Width;

                TopID.Value = "0";
                LeftID.Value = "0";
                GetThumb();
            }
        }

        private string GetTempDir()
        {
            string tempDir = WorkingDirectory != "" ? WorkingDirectory : "~/Temp";
            if (!System.IO.Directory.Exists(Server.MapPath(tempDir)))
                System.IO.Directory.CreateDirectory(Server.MapPath(tempDir));
            return tempDir;
        }

        public void SaveCroppedImageTo(string fileName)
        {
            if (System.IO.File.Exists(Server.MapPath(OutputURL)))
                System.IO.File.Copy(Server.MapPath(OutputURL), fileName);
        }

        public string GetDefaultPic()
        {
            return hidDefaultPic.Value;
        }

        public void btnScale_OnClick(object sender, EventArgs e)
        {
            Scale(ScaleRate);
        }

        public void btnFit_OnClick(object sender, EventArgs e)
        {
            if (System.IO.File.Exists(Server.MapPath(OriginalImageURL)))
            {
                System.Drawing.Image srcBitmap = new System.Drawing.Bitmap(Server.MapPath(OriginalImageURL));
                int rate = 100;
                //if (Height.Value <= Width.Value)
                //{
                //    if (srcBitmap.Height <= srcBitmap.Width)
                //        rate = (int)((float)Width.Value / srcBitmap.Width * 100);
                //    else
                //        rate = (int)((float)Height.Value / srcBitmap.Height * 100);
                //}
                //else
                //{
                //    if (srcBitmap.Height > srcBitmap.Width)
                //        rate = (int)((float)Width.Value / srcBitmap.Width * 100);
                //    else
                //        rate = (int)((float)Height.Value / srcBitmap.Height * 100);
                //}

                rate = (int)((float)Math.Max(Width.Value, Height.Value) / Math.Min(srcBitmap.Width, srcBitmap.Height) * 100);

                if (rate > 0)
                    Scale(rate);
            }
        }
    }
}